package me.stone.stanimeclient.page.search

import androidx.paging.PagingSource
import androidx.paging.PagingState
import me.stone.stanimeclient.core.data.domain.data.SearchFanDataListRepository
import me.stone.stanimeclient.core.model.FanIntroItem

class SearchPagingSource(
    private val query: String,
    private val repository: SearchFanDataListRepository
) : PagingSource<Int, FanIntroItem>() {

    override fun getRefreshKey(state: PagingState<Int, FanIntroItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, FanIntroItem> {
        val page = params.key ?: 1
        return try {
            val response = repository.searchFanDataList(query, page)
            val data = response.data ?: return LoadResult
                .Page(emptyList(), null, null)

            val prev = if (page > 1) page - 1 else null
            val next = if (data.totalPage > page) page + 1 else null
            LoadResult.Page(
                data = data.data,
                prevKey = prev,
                nextKey = next
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

}